package cn.itcast.sms.action;

import cn.itcast.crm.domain.Customer;
import cn.itcast.sms.utils.BaseAction;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;

import javax.print.attribute.standard.Media;
import javax.ws.rs.core.MediaType;
import java.io.IOException;

@Namespace("/")
@ParentPackage("json-default")
@Scope("protoType")
@Controller
//绑定邮箱的方法,发送激活邮件的方法在RegistAction中
public class MailAction extends BaseAction<Customer> {
    @Autowired
    private RedisTemplate<String ,String > redisTemplate;
    //属性驱动
    private String activeCode;

    public void setActiveCode(String activeCode) {
        this.activeCode = activeCode;
    }
    @Action(value ="customer_activeMail",results = {@Result(name="success", type="redirect",location = "registSuccess.html")})
    public String CustomerMail() throws IOException {
        ServletActionContext.getResponse().setContentType(
                "text/html;charset=utf-8");
        //先判断激活码是否有效
        String redisActiveCode = redisTemplate.opsForValue().get(model.getTelephone());
        System.out.println(redisActiveCode);
        if(redisActiveCode==null || !activeCode.equals(redisActiveCode)){
            //激活码无效
            ServletActionContext.getResponse().getWriter().print("激活码无效,请返回系统重新绑定");
        }else{
          //调用crm 系统,先查找当前用户是否已经绑定了邮箱
            Customer customer= WebClient.create("http://localhost:8081/crm_management/service/customerService/customerByTelephone/"+model.getTelephone()).
                    accept(MediaType.APPLICATION_JSON).get(Customer.class);
            if(customer.getType() == null || customer.getType() != 1){
                //没有绑定
                WebClient.create("http://localhost:8081/crm_management/service/customerService/customerUpdteType?telephone="+model.getTelephone()).type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).put(null);
                ServletActionContext.getResponse().getWriter()
                        .println("邮箱绑定成功！");
                ServletActionContext.getResponse().setHeader("Refresh","5;http://localhost:8082/index.html");
            }else{
                ServletActionContext.getResponse().getWriter().print("当前用户已经绑定邮箱,请勿重复绑定");
            }
            //删除激活码
            redisTemplate.delete(model.getTelephone());

        }
        return SUCCESS;

    }
}
